import axios, { AxiosError } from 'axios';

const http = axios.create({
  baseURL: '',
  timeout: 20000
});

http.interceptors.request.use(config => {
  // 可在此追加 token / trace id
  return config;
});

http.interceptors.response.use(
  resp => resp.data,
  (error: AxiosError) => {
    const status = error.response?.status;
    const url = error.config?.url;
    console.error('[HTTP ERROR]', status, url, error.message);
    // 统一包装错误信息
    return Promise.reject(
      new Error(
        (error as any)?.response?.data?.msg || `请求失败(${status || '网络错误'}) - ${url}`
      )
    );
  }
);

export default http;
// 便捷函数：保持与页面使用一致
export async function apiGet<T=any>(url: string, config?: any): Promise<T> {
  return http.get(url, config);
}
export async function apiPost<T=any>(url: string, data?: any, config?: any): Promise<T> {
  return http.post(url, data, config);
}
